package com.paireach.szwolaiyun.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.paireach.szwolaiyun.R;
import com.paireach.szwolaiyun.fragmentall.DcInSideQueueFragment;
import com.paireach.szwolaiyun.fragmentall.DcQueueOutSideFragment;
import com.paireach.szwolaiyun.fragmentall.DcStartDischargeCargoFragment;
import com.paireach.szwolaiyun.fragmentall.InGoodsReceiptFactoryQueueFragment;
import com.paireach.szwolaiyun.fragmentall.InGoodsReceiptFactoryQueueScanBarCodeFragment;
import com.paireach.szwolaiyun.fragmentall.InsideTheLoadFactoryQueueFragment;
import com.paireach.szwolaiyun.fragmentall.InsideTheLoadFactoryQueueScanBarCodeFragment;
import com.paireach.szwolaiyun.fragmentall.OutGoodsReceiptFactoryQueueFragment;
import com.paireach.szwolaiyun.fragmentall.OutGoodsReceiptFactoryQueueScanBarCodeFragment;
import com.paireach.szwolaiyun.fragmentall.OutsideTheLoadFactoryQueueFragment;
import com.paireach.szwolaiyun.fragmentall.OutsideTheLoadFactoryQueueScanBarCodeFragment;
import com.paireach.szwolaiyun.receiver.StatusJumpReceiver;
import com.paireach.szwolaiyun.sz_common_widget.activity.BaseActivity;

import szwolaiyun.paireach.com.szwolaizhuang.model.business.DriveOrder;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.HttpErrorEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.HttpSuccessEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.requestTag.RequestTag;
import szwolaiyun.paireach.com.szwolaizhuang.net.WayBillRequest;

/**
 * 設計圖的D界面，主要功能如下：
 * 1.裝貨工廠：工廠外排隊，工廠外等待進入，工廠内排隊，工廠内等待裝貨
 * 2.收貨工廠：工廠外排隊，工廠外等待進入，工廠内排隊，工廠内等待卸貨
 * 3.DC收貨：工廠外排隊，工廠外等待進入，工廠内排隊（此時已經有條碼了），沒有工廠内等待卸貨這個過程（界面）
 */
public class Activity_D extends BaseActivity {

    private int stateCode;
    private String orderNo;
    private ProgressBar bar;
    private FrameLayout frameLayout;
    private String dcDeptType;
    private TextView txt_error;

    private ImageView backView;
    private TextView tvTitleView;
    private RelativeLayout rl_layout_top;

    private StatusJumpReceiver receiver;
    private AutoFinishReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity__d);
        sendBroadcast(new Intent("com.paireach.szwolaiyun.ACTION_AUTO_FINISH"));
        IntentFilter mFilter = new IntentFilter("com.paireach.szwolaiyun.ACTION_AUTO_FINISH");
        mReceiver = new AutoFinishReceiver();
        registerReceiver(mReceiver, mFilter);
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                DriveOrder driveOrder = (DriveOrder) bundle.getSerializable("DriveOrder");
                stateCode = driveOrder.getOrderStateCode();
                orderNo = driveOrder.getOrderNo();
                dcDeptType = driveOrder.getDcDeptType();
            }
        }
        receiver = new StatusJumpReceiver(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.paireach.szwolaiyun.ACTION_JUMP");
        registerReceiver(receiver, filter);
        bar.setVisibility(View.VISIBLE);
        frameLayout.setVisibility(View.GONE);
        txt_error.setVisibility(View.GONE);
        if (stateCode == 224 || stateCode == 226) {
            new WayBillRequest().canDriverEnterToLoadGoods(orderNo);
        } else if (stateCode == 236 || stateCode == 238) {
            new WayBillRequest().canDriverEnterToReceiptGoods(orderNo);
        }
    }

    private void initView() {
        bar = (ProgressBar) findViewById(R.id.progressBar);
        frameLayout = (FrameLayout) findViewById(R.id.frame);
        txt_error = (TextView) findViewById(R.id.txt_error);
        backView = (ImageView) findViewById(R.id.layout_top_back);
        tvTitleView = (TextView) findViewById(R.id.layout_top_change);
        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                finish();
                //上面的有可能没有销毁D，
                Activity_D.this.finish();
            }
        });
        rl_layout_top = (RelativeLayout) findViewById(R.id.rl_layout_top);
        rl_layout_top.setVisibility(View.GONE);
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        if (event.getRequestTag() == RequestTag.CAN_LOAD_ENTER ||
                event.getRequestTag() == RequestTag.CAN_RECEIPT_ENTER ||
                event.getRequestTag() == RequestTag.GET_ORDER_DETAIL) {
            bar.setVisibility(View.GONE);
            frameLayout.setVisibility(View.GONE);
            txt_error.setVisibility(View.VISIBLE);
            txt_error.setText(event.getErrorMessage());
            showToast(event.getErrorMessage());
        }
    }

    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        txt_error.setVisibility(View.GONE);
        rl_layout_top.setVisibility(View.VISIBLE);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (event.getRequestTag() == RequestTag.CAN_LOAD_ENTER) {
            //判断装货工厂的进场状态和装货状态
            bar.setVisibility(View.GONE);
            frameLayout.setVisibility(View.VISIBLE);
            if (event.getJson().equals("0")) {
                //等待状态
                if (stateCode == 224) {
                    tvTitleView.setText("装货厂外排队");
                    OutsideTheLoadFactoryQueueFragment fragment2 = new OutsideTheLoadFactoryQueueFragment();
                    transaction.replace(R.id.frame, fragment2, OutsideTheLoadFactoryQueueFragment.TAG).commit();
                } else if (stateCode == 226) {
                    tvTitleView.setText("装货厂内排队");
                    InsideTheLoadFactoryQueueFragment fragment2 = new InsideTheLoadFactoryQueueFragment();
                    transaction.replace(R.id.frame, fragment2, InsideTheLoadFactoryQueueFragment.TAG).commit();
                }
            } else {
                //准许进入
                if (stateCode == 224) {
                    tvTitleView.setText("入厂提示");
                    OutsideTheLoadFactoryQueueScanBarCodeFragment fragment = OutsideTheLoadFactoryQueueScanBarCodeFragment.getInstance(orderNo);
                    transaction.replace(R.id.frame, fragment, OutsideTheLoadFactoryQueueScanBarCodeFragment.TAG).commit();
                } else if (stateCode == 226) {
                    tvTitleView.setText("装货提示");
                    InsideTheLoadFactoryQueueScanBarCodeFragment fragment = InsideTheLoadFactoryQueueScanBarCodeFragment.getInstance(orderNo);
                    transaction.replace(R.id.frame, fragment, InsideTheLoadFactoryQueueScanBarCodeFragment.TAG).commit();
                }
            }
        } else if (event.getRequestTag() == RequestTag.CAN_RECEIPT_ENTER) {
            //判断卸货工厂的进场状态和卸货状态
            bar.setVisibility(View.GONE);
            frameLayout.setVisibility(View.VISIBLE);
            if (event.getJson().equals("0")) {
                //等待状态 红灯状态
                if (stateCode == 236) {
                    if (dcDeptType.equals("dc")) {
                        tvTitleView.setText("收货厂外排队");
                        DcQueueOutSideFragment fragment = new DcQueueOutSideFragment();
                        transaction.replace(R.id.frame, fragment, DcQueueOutSideFragment.TAG).commit();
                    } else if (dcDeptType.equals("factory")) {
                        tvTitleView.setText("收货厂外排队");
                        OutGoodsReceiptFactoryQueueFragment fragment = new OutGoodsReceiptFactoryQueueFragment();
                        transaction.replace(R.id.frame, fragment, OutGoodsReceiptFactoryQueueFragment.TAG).commit();
                    }
                } else if (stateCode == 238) {
                    if (dcDeptType.equals("dc")) {
                        rl_layout_top.setVisibility(View.GONE);
                        DcStartDischargeCargoFragment fragment = DcStartDischargeCargoFragment.getInstance(orderNo);
                        transaction.replace(R.id.frame, fragment, DcStartDischargeCargoFragment.TAG).commit();
                    } else if (dcDeptType.equals("factory")) {
                        tvTitleView.setText("收货工厂内排队");
                        InGoodsReceiptFactoryQueueFragment fragment = new InGoodsReceiptFactoryQueueFragment();
                        transaction.replace(R.id.frame, fragment, InGoodsReceiptFactoryQueueFragment.TAG).commit();
                    }
                }
            } else {
                //准许进入 绿灯状态
                if (stateCode == 236) {
                    if (dcDeptType.equals("dc")) {
                        rl_layout_top.setVisibility(View.GONE);
                        Intent intent = new Intent(this, Activity_E.class);
                        intent.putExtra("orderNumber", orderNo);
                        startActivity(intent);
                        //finish()有可能没有销毁D，
                        Activity_D.this.finish();
                    } else if (dcDeptType.equals("factory")) {
                        tvTitleView.setText("入厂提示");
                        OutGoodsReceiptFactoryQueueScanBarCodeFragment fragment = OutGoodsReceiptFactoryQueueScanBarCodeFragment.getInstance(orderNo);
                        transaction.replace(R.id.frame, fragment, OutGoodsReceiptFactoryQueueScanBarCodeFragment.TAG).commit();
                    }
                } else if (stateCode == 238) {
                    if (dcDeptType.equals("dc")) {
                        tvTitleView.setText("等待卸货");
                        DcInSideQueueFragment fragment = DcInSideQueueFragment.getInstance(orderNo);
                        transaction.replace(R.id.frame, fragment, OutGoodsReceiptFactoryQueueFragment.TAG).commit();
                    } else if (dcDeptType.equals("factory")) {
                        tvTitleView.setText("收货提示");
                        InGoodsReceiptFactoryQueueScanBarCodeFragment fragment = InGoodsReceiptFactoryQueueScanBarCodeFragment.getInstance(orderNo);
                        transaction.replace(R.id.frame, fragment, InGoodsReceiptFactoryQueueScanBarCodeFragment.TAG).commit();
                    }
                }
            }
        }
    }

    private class StatusJumpReceiver extends BroadcastReceiver {

        private String action = "com.paireach.szwolaiyun.ACTION_JUMP";
        private String orderNumber;
        private Activity mContext;

        public StatusJumpReceiver(Activity mContext) {
            this.mContext = mContext;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(action)) {
                mContext.removeStickyBroadcast(new Intent("com.paireach.szwolaiyun.ACTION_JUMP"));
                //解析数据
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    orderNumber = bundle.getString("orderCode");
                    Intent intent1 = new Intent(Activity_D.this, Activity_B.class);
                    intent1.putExtra("orderNumber", orderNumber);
                    //finish()的有可能没有销毁D，
                    Activity_D.this.finish();
                    startActivity(intent1);
//                    finish();
                }
            }
        }
    }

    private class AutoFinishReceiver extends BroadcastReceiver {
        private String action2 = "com.paireach.szwolaiyun.ACTION_AUTO_FINISH";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(action2)) {
//                finish();

                //上面的有可能没有销毁D，
                Activity_D.this.finish();
            }
        }
    }

}
